﻿using clf.weighing.entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using MyHelper;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using Brushes = System.Windows.Media.Brushes;
using Image = System.Windows.Controls.Image;
using Timer = System.Threading.Timer;
using PrintDialog = System.Windows.Controls.PrintDialog;
using UserControl = System.Windows.Controls.UserControl;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using Action = System.Action;
using ExclApplication = Microsoft.Office.Interop.Excel.Application;
using System.Reflection;


namespace weighing
{
    /// <summary>
    /// PrintEXCLWindow.xaml 的交互逻辑
    /// </summary>
    public partial class PrintEXCLWindow : GlowWindow
    {
        #region variables
        private WeighingBillVo? mWeighingBillVo = null;
        private WeighingBill? mWeighingBill = null;
        private Int64 mBillId;
        private bool isAutoPrint;
        /// <summary>
        /// after 3s close this window 
        /// </summary>
        private Timer mTime;
        private bool isClickPrint = false;
        private System.Timers.Timer CuontDownPrintTimer;
        #endregion

        public PrintEXCLWindow(Int64 billId)
        {
            InitializeComponent();
            mBillId = billId;

            CommonFunction.ShowCustomIcon(this);
        }

        #region window event
        private void Print_Window_Loaded(object sender, RoutedEventArgs e)
        {
            string msg = "没有要打印的磅单 ，窗口将闭关。";
            if (mBillId <= 0)
            {
                CommonFunction.AlertInfo(msg, this);
                this.Close();
                return;
            }
            else
            {
                mWeighingBill = WeighingBillDao.Instance.FindById(mBillId);
                if (mWeighingBill == null)
                {
                    CommonFunction.AlertInfo(msg, this);
                    this.Close();
                    return;
                }
                else
                {
                    mWeighingBillVo = new WeighingBillVo(mWeighingBill);
                    if (mWeighingBill.type == (int)WeightingBillType.Buy)
                    {
                        isAutoPrint = App.Config.BillPrintConfig.EnableUnloadBill;
                    }
                    else if (mWeighingBill.type == (int)WeightingBillType.Sale)
                    {
                        isAutoPrint = App.Config.BillPrintConfig.EnableLoadBill;
                    }
                    else
                    {
                        isAutoPrint = false;
                    }
                }
            }
        }

        private void Print_Window_ContentRendered(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(GetPrintExclFile()))
            {
                this.printPanel.Children.Clear();
                this.printPanel.Children.Add(new TextBlock()
                {
                    Text = "自定义电子表格打印，界面无法显示要打印的内容,请直接打印",
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    FontSize = 14,
                    Foreground = Brushes.DarkGray,
                });
            }
            else
            {
                if (mWeighingBill.type == (int)WeightingBillType.Buy)
                {
                    this.printPanel.Children.Clear();
                    this.printPanel.Children.Add(new InPrint() { DataContext = mWeighingBillVo });
                }
                else if (mWeighingBill.type == (int)WeightingBillType.Sale)
                {
                    this.printPanel.Children.Clear();
                    this.printPanel.Children.Add(new OutPrint() { DataContext = mWeighingBillVo });
                }
                else
                {
                    this.printPanel.Children.Clear();
                    this.printPanel.Children.Add(new OrtherPrintUc() { DataContext = mWeighingBillVo });
                }
            }
        }

        private void Print_Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            mTime?.Dispose();
            CuontDownPrintTimer?.Dispose();
        }

        private void Print_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.Close();
            }
        }
        #endregion



        /// <summary>
        /// check print times
        /// </summary>
        /// <returns></returns>
        private bool VerifyPrintTimes()
        {
            if (mWeighingBill?.type == (int)WeightingBillType.ExitSlip)
            {
                //unlimited exit slip print times
                return true;
            }
            if (mWeighingBill?.type == (int)WeightingBillType.Buy)
            {
                return (mWeighingBill?.printTimes ?? 0) < App.Config.BillPrintConfig.LimitInPrintTimes;
            }
            else if (mWeighingBill?.type == (int)WeightingBillType.Sale)
            {
                return (mWeighingBill?.printTimes ?? 0) < App.Config.BillPrintConfig.LimitOutPrintTimes;
            }
            else
            {
                //other type unlimited print times
                return true;
            }

        }



        /// <summary>
        /// cunt down automatic print
        /// </summary>
        private void AutoPrint()
        {
            if (!isAutoPrint) return;
            int autoSeconds = App.Config.BillPrintConfig.AutoPrintInterval;
            if (CuontDownPrintTimer == null)
            {
                CuontDownPrintTimer = new System.Timers.Timer(1000);
                CuontDownPrintTimer.Elapsed += (sender, args) =>
                {
                    autoSeconds--;
                    Thread.Sleep(1000);
                    if (autoSeconds <= 0)
                    {
                        CuontDownPrintTimer?.Stop();
                        this.Dispatcher.Invoke(() =>
                        {
                            this.PrintBtn.Content = "打印";
                            Print();
                            this.PrintBtn.IsEnabled = false;
                        });
                    }
                    else
                    {
                        this.PrintBtn.IsEnabled = false;
                        this.PrintBtn.Content = "打印 " + autoSeconds + "s";
                    }
                };
                CuontDownPrintTimer.Start();
            }
        }

        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            isClickPrint = true;
            Print();          
        }

        //未自定义磅章
        private void Print() {
            var exclFile = GetPrintExclFile();
            if (string.IsNullOrEmpty(exclFile))
            {
                PrintDefault();
            }
            else
            {
                PrintEXCL();
            }
        }


        //打印默认的内容
        private void PrintDefault()
        {
            if (isAutoPrint == false && isClickPrint == false)
            {
                return;
            }
            var cb = this.printPanel.Children[0] as TextBlock;
            if (cb != null && cb.Name == "NoCustomerContent")
            {
                Growl.Info("没有要打印的内容", this.Name);
                return;
            }
            this.PrintBtn.IsEnabled = false;
            try
            {
                PrintQueue? printQueue = CommonFunction.GetPrintQueue((WeightingBillType)mWeighingBill.type);
                if (printQueue == null || printQueue.IsOffline == true)
                {
                    throw new Exception("打印机不可用！");
                }
                string description = "磅单打印" ;
                var printDialog = new PrintDialog
                {
                    CurrentPageEnabled = true,
                    PageRange = new PageRange(1),
                    PrintQueue = printQueue,
                };

                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    //打印
                    printDialog.PrintVisual(this.printPanel.Children[0], description);               
                }));

                Growl.Info("打印成功");

                mWeighingBillVo.PrintTimes++;                
                mWeighingBillVo.LastUpdateTime = mWeighingBillVo.PrintDateTime;
                mWeighingBillVo.Type = null;
                WeighingBillDao.Instance.Update(mWeighingBillVo.mWeighingBill);

                //after 3s close this window
                DelayCloseWin(3);
                this.Close();
            }
            catch (Exception e)
            {
                string msg = $"打印出错：{e.Message}";
                ConsoleHelper.writeLine(msg);
                Growl.Error(msg, this.Name);
                Log.Error(msg);
                CommonFunction.SpeakAsync(msg);
            }
            this.PrintBtn.IsEnabled = true;
        }

        public void PrintEXCL()
        {
            if (isAutoPrint == false && isClickPrint == false)
            {
                return;
            }
            var exclFile = GetPrintExclFile();
        
            this.PrintBtn.IsEnabled = false;
            try
            {
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    //打印
                    // 创建 Excel 应用程序实例
                    ExclApplication excelApp = new ExclApplication();
                    Worksheet worksheet = null;
                    Workbook workbook = null;
                    try
                    {
                        // 创建一个新的工作簿
                        workbook = excelApp.Workbooks.Open(exclFile);
                        worksheet = (Worksheet)workbook.Sheets[1];

                        //替换打印内容
                        SetBillDataToExcl(worksheet);

                        //打开 Excl 
                        //excelApp.Visible = true;
                        //worksheet.PrintPreview();
                        worksheet.PrintOutEx(false);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("发生错误:" + ex.Message);
                    }

                }));

                mWeighingBillVo.PrintTimes++;
                mWeighingBillVo.LastUpdateTime = mWeighingBillVo.PrintDateTime;
                mWeighingBillVo.Type = null;
                WeighingBillDao.Instance.Update(mWeighingBillVo.mWeighingBill);

                Growl.Info("打印成功", this.Name);
                //after 3s close this window
                DelayCloseWin(3);
                this.Close();
            }
            catch (Exception e)
            {
                string msg = $"打印出错：{e.Message}";
                ConsoleHelper.writeLine(msg);
                Growl.Error(msg, this.Name);
                Log.Error(msg);
                CommonFunction.SpeakAsync(msg);
            }
            this.PrintBtn.IsEnabled = true;
        }

        private void DelayCloseWin(int second)
        {
            mTime = new Timer(delegate
            {
                this.Dispatcher.BeginInvoke(new Action(delegate
                {
                    this.Close();
                }), System.Windows.Threading.DispatcherPriority.Send);
            }, null, second * 1000, Timeout.Infinite);
        }


        private string GetPrintExclFile()
        {
            if (mWeighingBill == null) return "";
            var file = "";
            if (mWeighingBill.type == (int)WeightingBillType.Buy)
            {
                file = App.Config.BillPrintConfig.BuyExclFile;
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Sale)
            {
                file = App.Config.BillPrintConfig.SaleExclFile;
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Self)
            {
                file = App.Config.BillPrintConfig.SelfExclFile;
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Foreign)
            {
                file = App.Config.BillPrintConfig.ForeginExclFile;
            }
            else if (mWeighingBill.type == (int)WeightingBillType.Mixture)
            {
                file = App.Config.BillPrintConfig.MixtureExclFile;
            }
            else { file = ""; }
            return file;
        }

        private void SetBillDataToExcl(Worksheet worksheet)
        {

            var nameDic = CommonFunction.GetBillTitleFieldNameDic();
            if (nameDic.Count() <= 0)
            {
                Growl.Clear();
                Growl.Error("无法获取磅单变量与数据字段的对映关系");
                return;
            }

            // 获取总行数
            int totalRows = worksheet.UsedRange.Rows.Count;
            // 获取总列数
            int totalColumns = worksheet.UsedRange.Columns.Count;

            #region 替换打印内容
            Debug.WriteLine("开始替换打印内容");
            mWeighingBill.printDateTime = DateTime.Now;
            for (int i = 1; i <= totalRows; i++)
            {
                for (int j = 1; j <= totalColumns; j++)
                {
                    var value = "";
                    Microsoft.Office.Interop.Excel.Range? dataRanger = worksheet.Cells[i, j] as Microsoft.Office.Interop.Excel.Range;
                    if (dataRanger == null) continue;

                    string str = dataRanger.Text?.ToString() ?? "";
                    if (string.IsNullOrEmpty(str))
                    {
                        str = dataRanger.Value?.ToString() ?? "";
                    }
                    if (string.IsNullOrEmpty(str))
                    {
                        str = dataRanger.Value2?.ToString() ?? "";
                    }
                    Debug.WriteLine("value:" + dataRanger.Value?.ToString() ?? "");
                    Debug.WriteLine("value2" + dataRanger.Value2?.ToString() ?? "");

                    if (str.StartsWith("[") && str.EndsWith("]"))
                    {
                        var title = str.Replace("[", "").Replace("]", "");
                        string fieldName = nameDic.Keys.Contains(title) ? nameDic[title] : "";
                        if (string.IsNullOrEmpty(fieldName))
                        {
                            continue;
                        }
                        value = "";
                        FieldInfo? fi = mWeighingBill.GetType().GetField(fieldName);
                        if (fi != null)
                        {
                            if (fi.GetValue(mWeighingBill) is DateTime dt)
                            {
                                value = dt.ToString("yyyy-MM-dd hh:mm:ss") ?? "";
                            }
                            else
                            {
                                value = fi.GetValue(mWeighingBill)?.ToString() ?? "";
                            }
                        }
                        worksheet.Cells[i, j] = value.Replace("/", "-");
                    }
                }
            }

            Debug.WriteLine("结束替换打印内容");
            #endregion
        }

    }
}
